<template>
  <view class="edit-page">
    <view class="section">
      <view class="label">转盘标题</view>
      <input 
        class="input" 
        v-model="title" 
        placeholder="请输入转盘名称"
        placeholder-class="placeholder"
      />
    </view>

    <view class="section">
      <view class="label">转盘选项（共{{ items.length }}个）</view>
      <view class="item" v-for="(it, i) in items" :key="i">
        <button class="del" @click="remove(i)">×</button>
        <input 
          class="name" 
          v-model="it.text" 
          placeholder="请输入选项名称"
          placeholder-class="placeholder"
        />
        <view class="color-picker" @click="showColorPicker(i)">
          <view class="color-preview" :style="{ backgroundColor: it.color }"></view>
        </view>
      </view>
      <button class="add" @click="add">＋ 添加新的选项</button>
      
      <!-- 快速模板 -->
      <view class="templates">
        <button @click="loadTemplate('food')">🍔 今天吃什么</button>
        <button @click="loadTemplate('game')">🎮 玩什么游戏</button>
        <button @click="loadTemplate('movie')">🎬 看什么电影</button>
      </view>
    </view>

    <!-- 底部悬浮按钮 -->
    <view class="footer-fixed">
      <button class="btn-cancel" @click="more">更多</button>
      <button class="btn-save" @click="save">保存 {{ items.length }} 项</button>
    </view>
    
    <!-- 颜色选择器弹窗 -->
    <view v-if="showColorModal" class="color-modal" @click.self="closeColorPicker">
      <view class="color-panel" @click.stop>
        <view class="color-panel-title">
          <text>选择颜色</text>
          <text class="color-tip">点击色块即可应用</text>
        </view>
        <view class="color-grid">
          <view 
            v-for="(color, idx) in colorPalette" 
            :key="idx"
            class="color-item"
            :class="{ active: currentEditingColor === color.toUpperCase() }"
            :style="{ backgroundColor: color }"
            @click.stop="selectColor(color)"
          >
            <text v-if="currentEditingColor === color.toUpperCase()" class="check-icon">✓</text>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, onShow } from 'vue'
import { onLoad } from '@dcloudio/uni-app'

const title = ref('')
const items = ref([])

// 扩展调色盘 - 24色
const colorPalette = [
  '#FF6B6B', '#FF8787', '#FFA07A', '#FFB347', 
  '#FFD93D', '#FFE66D', '#A8E6CF', '#7FFF4D',
  '#6BCF7F', '#4ECDC4', '#45B7D1', '#4D9CFF',
  '#5DADE2', '#6C5CE7', '#9370DB', '#A29BFE',
  '#FF69B4', '#FF85C0', '#F06292', '#E91E63',
  '#FF5252', '#FF8C00', '#FFA500', '#FFB6C1'
]

// 颜色选择器状态
const showColorModal = ref(false)
const currentEditingIndex = ref(-1)
const currentEditingColor = ref('')

function load() {
  console.log('🔄 页面加载...')
  const data = uni.getStorageSync('wheel:data')
  console.log('📦 存储数据:', data)
  if (data && data.items) {
    title.value = data.title || ''
    items.value = data.items
  } else {
    items.value = [
      { text: '选项1', color: '#FF7757' },
      { text: '选项2', color: '#7FFF4D' },
      { text: '选项3', color: '#4D9CFF' }
    ]
  }
  console.log('✅ 加载完成，选项数:', items.value.length)
}

function add() {
  console.log('➕ 添加选项')
  const randomColor = colorPalette[Math.floor(Math.random() * colorPalette.length)]
  items.value.push({ text: `选项${items.value.length + 1}`, color: randomColor })
  console.log('✅ 新选项数量:', items.value.length)
  // 触觉反馈
  uni.vibrateShort({ type: 'light' })
}

function remove(i) {
  console.log('🗑️ 删除选项:', i)
  if (items.value.length <= 2) {
    uni.showToast({ title: '至少保留2个选项', icon: 'none' })
    return
  }
  items.value.splice(i, 1)
  console.log('✅ 删除后选项数:', items.value.length)
  // 触觉反馈
  uni.vibrateShort({ type: 'medium' })
}

// 显示颜色选择器
function showColorPicker(index) {
  console.log('🎨 打开颜色选择器，索引:', index)
  
  // 检查索引有效性
  if (index < 0 || index >= items.value.length) {
    console.error('❌ 无效的索引:', index)
    return
  }
  
  currentEditingIndex.value = index
  // 标准化颜色值为大写，确保对比正确
  currentEditingColor.value = items.value[index].color.toUpperCase()
  console.log('🎨 当前颜色:', currentEditingColor.value)
  showColorModal.value = true
  // 触觉反馈
  uni.vibrateShort({ type: 'light' })
}

// 选择颜色（直接确认）
function selectColor(color) {
  console.log('🖱️ 选择颜色:', color)
  currentEditingColor.value = color.toUpperCase()
  console.log('✅ 当前颜色更新为:', currentEditingColor.value)
  
  // 立即更新颜色（不保存到本地存储）
  if (currentEditingIndex.value >= 0) {
    const index = currentEditingIndex.value
    console.log('更新颜色:', {
      index,
      oldColor: items.value[index].color,
      newColor: currentEditingColor.value
    })
    
    // 直接修改颜色值（不调用 save）
    items.value[index].color = currentEditingColor.value
    
    uni.showToast({ 
      title: '颜色已更新', 
      icon: 'success',
      duration: 800
    })
  }
  
  // 触觉反馈
  uni.vibrateShort({ type: 'medium' })
  
  // 延迟关闭弹窗，让用户看到选中效果
  setTimeout(() => {
    closeColorPicker()
  }, 300)
}

// 确认颜色
function confirmColor() {
  if (currentEditingIndex.value >= 0 && currentEditingColor.value) {
    const index = currentEditingIndex.value
    console.log('更新颜色:', {
      index,
      oldColor: items.value[index].color,
      newColor: currentEditingColor.value
    })
    
    // 直接修改并强制更新
    items.value[index].color = currentEditingColor.value
    
    // 立即保存到本地存储
    save()
    
    uni.showToast({ 
      title: '颜色已更新', 
      icon: 'success',
      duration: 1000
    })
  }
  closeColorPicker()
  // 触觉反馈
  uni.vibrateShort({ type: 'medium' })
}

// 关闭颜色选择器
function closeColorPicker() {
  showColorModal.value = false
  currentEditingIndex.value = -1
  currentEditingColor.value = ''
}

function loadTemplate(type) {
  const templates = {
    food: [
      { text: '火锅', color: '#FF7757' },
      { text: '烧烤', color: '#FF8C00' },
      { text: '麻辣烫', color: '#FF69B4' },
      { text: '海底捞', color: '#4D9CFF' },
      { text: '肯德基', color: '#FFD700' }
    ],
    game: [
      { text: '王者荣耀', color: '#FFD700' },
      { text: '和平精英', color: '#7FFF4D' },
      { text: '原神', color: '#4D9CFF' },
      { text: '英雄联盟', color: '#FF69B4' }
    ],
    movie: [
      { text: '动作片', color: '#FF7757' },
      { text: '科幻片', color: '#4D9CFF' },
      { text: '喜剧片', color: '#FFD700' },
      { text: '爱情片', color: '#FF69B4' }
    ]
  }
  
  items.value = templates[type] || items.value
  uni.showToast({ title: '模板已加载', icon: 'success' })
}

function more() {
  console.log('📱 点击更多按钮')
  uni.showToast({ title: '更多功能开发中', icon: 'none' })
}

function save() {
  console.log('💾 保存数据...')
  // 过滤掉空选项
  const validItems = items.value.filter(item => item.text.trim())
  if (validItems.length < 2) {
    uni.showToast({ title: '至少需要2个有效选项', icon: 'none' })
    return
  }
  
  const data = { title: title.value, items: validItems }
  console.log('💾 保存数据:', data)
  uni.setStorageSync('wheel:data', data)
  uni.showToast({ title: '已保存', icon: 'success' })
  console.log('✅ 保存成功')
  setTimeout(() => uni.navigateBack(), 500)
}

onLoad(load)
</script>

<style lang="scss" scoped>
.edit-page {
  min-height: 100vh;
  background: linear-gradient(135deg, #FFF5F7 0%, #F3E8FF 100%);
  padding: 32rpx;
  padding-bottom: 160rpx; // 增加底部空间，为悬浮按钮留出位置
}

.section {
  background: rgba(255, 255, 255, 0.95);
  backdrop-filter: blur(10rpx);
  border-radius: 32rpx;
  padding: 32rpx;
  margin-bottom: 32rpx;
  box-shadow: 0 8rpx 32rpx rgba(255, 182, 193, 0.15);
}

.label {
  font-size: 32rpx;
  font-weight: 600;
  margin-bottom: 24rpx;
  background: linear-gradient(135deg, #D87093 0%, #9370DB 100%);
  background-clip: text;
  -webkit-background-clip: text;
  -webkit-text-fill-color: transparent;
  letter-spacing: 1rpx;
}

.input {
  background: linear-gradient(135deg, #FFE5EC 0%, #F3E8FF 100%);
  border: 2rpx solid #fff;
  border-radius: 20rpx;
  padding: 0 24rpx;
  font-size: 30rpx;
  color: #333;
  height: 88rpx;
  box-shadow: 0 4rpx 16rpx rgba(255, 182, 193, 0.1);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  
  &:focus {
    box-shadow: 0 4rpx 20rpx rgba(255, 182, 193, 0.25);
  }
}

.placeholder {
  color: #B8A8B8;
  font-size: 30rpx;
}

.item {
  display: flex;
  align-items: center;
  gap: 12rpx;
  margin-bottom: 16rpx;
}

.del {
  width: 72rpx;
  height: 72rpx;
  border-radius: 16rpx;
  background: linear-gradient(135deg, #FFE5EC 0%, #FFCCCC 100%);
  color: #D87093;
  border: 2rpx solid #fff;
  font-size: 36rpx;
  font-weight: bold;
  box-shadow: 0 4rpx 12rpx rgba(255, 182, 193, 0.2);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  line-height: 1;
  
  &::after {
    border: none;
  }
  
  &:active {
    transform: scale(0.9);
    box-shadow: 0 2rpx 8rpx rgba(255, 182, 193, 0.25);
  }
}

.name {
  flex: 1;
  background: linear-gradient(135deg, #FFE5EC 0%, #F3E8FF 100%);
  border: 2rpx solid #fff;
  border-radius: 16rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  color: #333;
  height: 72rpx;
  box-shadow: 0 4rpx 12rpx rgba(255, 182, 193, 0.1);
  
  // placeholder 样式继承 .placeholder 类
}

.color-picker {
  width: 72rpx;
  height: 72rpx;
  border: 4rpx solid #fff;
  border-radius: 16rpx;
  overflow: hidden;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.2);
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  
  &:active {
    transform: scale(0.92);
  }
}

.color-preview {
  width: 100%;
  height: 100%;
}

.add {
  width: 100%;
  background: linear-gradient(135deg, #D87093 0%, #9370DB 100%);
  color: #fff;
  border-radius: 20rpx;
  padding: 20rpx 0;
  border: none;
  font-size: 28rpx;
  font-weight: 600;
  margin-top: 16rpx;
  box-shadow: 0 6rpx 20rpx rgba(216, 112, 147, 0.3);
  letter-spacing: 1rpx;
  transition: all 0.35s cubic-bezier(0.4, 0, 0.2, 1);
  
  &::after {
    border: none;
  }
  
  &:active {
    transform: scale(0.97);
    box-shadow: 0 4rpx 16rpx rgba(216, 112, 147, 0.35);
  }
}

.templates {
  display: flex;
  gap: 12rpx;
  margin-top: 24rpx;
  
  button {
    flex: 1;
    background: linear-gradient(135deg, #FFE5EC 0%, #F3E8FF 100%);
    border: 2rpx solid #fff;
    border-radius: 16rpx;
    padding: 16rpx 8rpx;
    font-size: 24rpx;
    color: #8B7B8B;
    font-weight: 500;
    box-shadow: 0 4rpx 16rpx rgba(255, 182, 193, 0.15);
    transition: all 0.35s cubic-bezier(0.4, 0, 0.2, 1);
    
    &::after {
      border: none;
    }
    
    &:active {
      transform: scale(0.95);
      box-shadow: 0 2rpx 12rpx rgba(255, 182, 193, 0.2);
    }
  }
}

/* 悬浮底部按钮 */
.footer-fixed {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  display: flex;
  gap: 16rpx;
  padding: 20rpx 32rpx;
  padding-bottom: calc(20rpx + env(safe-area-inset-bottom));
  background: rgba(255, 255, 255, 0.98);
  backdrop-filter: blur(20rpx);
  box-shadow: 0 -4rpx 24rpx rgba(255, 182, 193, 0.15);
  z-index: 100;
}

.btn-cancel {
  flex: 0 0 auto;
  min-width: 140rpx;
  background: linear-gradient(135deg, #FFE5EC 0%, #F3E8FF 100%);
  border: 2rpx solid #fff;
  border-radius: 60rpx; // 胶囊形状
  padding: 18rpx 32rpx;
  font-size: 26rpx;
  font-weight: 500;
  color: #8B7B8B;
  box-shadow: 0 4rpx 16rpx rgba(255, 182, 193, 0.2);
  transition: all 0.35s cubic-bezier(0.4, 0, 0.2, 1);
  
  &::after {
    border: none;
  }
  
  &:active {
    transform: scale(0.95);
  }
}

.btn-save {
  flex: 1;
  background: linear-gradient(135deg, #D87093 0%, #9370DB 100%);
  color: #fff;
  border-radius: 60rpx; // 胶囊形状
  padding: 18rpx 32rpx;
  border: none;
  font-size: 28rpx;
  font-weight: 700;
  letter-spacing: 1rpx;
  box-shadow: 0 6rpx 24rpx rgba(216, 112, 147, 0.35);
  transition: all 0.35s cubic-bezier(0.4, 0, 0.2, 1);
  
  &::after {
    border: none;
  }
  
  &:active {
    transform: scale(0.95);
  }
}

/* 颜色选择器弹窗 */
.color-modal {
  position: fixed;
  inset: 0;
  background: rgba(0, 0, 0, 0.6);
  backdrop-filter: blur(4rpx);
  display: flex;
  align-items: flex-end;
  z-index: 999;
  animation: fadeIn 0.3s;
}

@keyframes fadeIn {
  from { opacity: 0; }
  to { opacity: 1; }
}

.color-panel {
  width: 100%;
  background: linear-gradient(135deg, #FFF5F7 0%, #F3E8FF 100%);
  border-top-left-radius: 48rpx;
  border-top-right-radius: 48rpx;
  padding: 40rpx 32rpx;
  padding-bottom: calc(40rpx + env(safe-area-inset-bottom));
  animation: slideUp 0.35s cubic-bezier(0.4, 0, 0.2, 1);
}

@keyframes slideUp {
  from {
    transform: translateY(100%);
  }
  to {
    transform: translateY(0);
  }
}

.color-panel-title {
  text-align: center;
  margin-bottom: 32rpx;
  
  text {
    display: block;
    font-size: 32rpx;
    font-weight: 700;
    background: linear-gradient(135deg, #D87093 0%, #9370DB 100%);
    background-clip: text;
    -webkit-background-clip: text;
    -webkit-text-fill-color: transparent;
  }
}

.color-tip {
  display: block !important;
  font-size: 24rpx !important;
  color: #999 !important;
  margin-top: 8rpx !important;
  font-weight: 400 !important;
  background: none !important;
  -webkit-text-fill-color: #999 !important;
}

.color-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 20rpx;
  margin-bottom: 32rpx;
}

.color-item {
  aspect-ratio: 1;
  border-radius: 16rpx;
  box-shadow: 0 4rpx 16rpx rgba(0, 0, 0, 0.15);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  border: 4rpx solid transparent;
  
  &.active {
    border-color: #fff;
    box-shadow: 0 6rpx 24rpx rgba(0, 0, 0, 0.25);
    transform: scale(1.1);
  }
  
  .check-icon {
    color: #fff;
    font-size: 32rpx;
    font-weight: bold;
    text-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.3);
  }
}

// 移除确认取消按钮样式（已不需要）
</style>


